<template>
  <div class="container_box">
    <!--  <el-tag type="info" style="margin-left:1rem;">添加规格值,请先搜索,如果有选项,必须先选定再确认</el-tag> -->
    <el-row>
      <el-autocomplete
        v-model="singleInputSpecName"
        :fetch-suggestions="querySearchAsyncSpecName"
        placeholder="请输入内容"
        value-key="spec_name"
        @select="handleSelectSpecName"
      />
      <el-button style="margin-left:1rem;" type="primary" @click="handleAddCustomSpecName()">添加自定义规格名</el-button>
    </el-row>
    <div v-if="systemSpecNameList.length">
      <el-row v-for="(item,index) in systemSpecNameList" :key="index" style="margin-top:0.5rem;">
        <div style="display:flex;flex-direction:row;">
          <el-tag type="info">{{ item.spec_name }}</el-tag>

          <div v-if="!item.specValueArray || item.specValueArray.length === 0" class="spec_value_array_box">
            暂无
          </div>
          <div v-if="item.specValueArray && item.specValueArray.length > 0" class="spec_value_array_box">
            <el-checkbox v-for="(specValueItem,key) in item.specValueArray" :key="key" v-model="specValueItem.isSelect" :label="specValueItem.spec_value" border size="medium" @change="handleChangeCheckBox(item,specValueItem)" />
          </div>

          <div class="action_box">
            <div v-if="showGoodsSpecNameId === item.goods_spec_name_id && isShowInputSpecValue" class="add_spec_value_box">
              <el-autocomplete
                v-model="singleInputSpecValue"
                style="width:200px;"
                :fetch-suggestions="querySearchAsyncSpecValue"
                placeholder="请输入内容"
                value-key="spec_value"
                @select="handleSelectSpecValue"
              />
              <el-button style="margin-left:1rem;" type="primary" size="small" @click="handToConfirmSpecValue(item)">确认</el-button>
              <el-button style="margin-left:1rem;" type="danger" size="small" @click="handToCancelSpecValue(item)">取消</el-button>
            </div>
            <el-button v-if="!isShowInputSpecValue" class="add_spec_value_box" type="primary" size="small" @click="handToAddSpecValue(item)">添加规格值</el-button>
          </div>

        </div>
      </el-row>
    </div>
    <div v-if="customSpecNameList.length">
      <el-row v-for="(item,index) in customSpecNameList" :key="index" style="margin-top:0.5rem;">
        <div style="display:flex;flex-direction:row;">

          <div style="display:flex;flex-direction:row;">
            <el-button type="warning" size="mini" @click="handleToRemoveCoustomSpecName(item,index)">移除</el-button>
            <el-tag type="info">{{ item.spec_name }}</el-tag>
          </div>

          <div v-if="!item.specValueArray || item.specValueArray.length === 0" class="spec_value_array_box">
            暂无
          </div>
          <div v-if="item.specValueArray && item.specValueArray.length > 0" class="spec_value_array_box">
            <el-checkbox v-for="(specValueItem,key) in item.specValueArray" :key="key" v-model="specValueItem.isSelect" :label="specValueItem.spec_value" border size="medium" @change="handleChangeCheckBox(item,specValueItem)" />
          </div>

          <div class="action_box">
            <div v-if="showGoodsSpecNameId === item.id && isShowInputSpecValue" class="add_spec_value_box">
              <el-autocomplete
                v-model="singleInputSpecValue"
                style="width:200px;"
                :fetch-suggestions="querySearchAsyncSpecValue"
                placeholder="请输入内容"
                value-key="spec_value"
                @select="handleSelectSpecValue"
              />
              <el-button style="margin-left:1rem;" type="primary" size="small" @click="handToConfirmSpecValue(item)">确认</el-button>
              <el-button style="margin-left:1rem;" type="danger" size="small" @click="handToCancelSpecValue(item)">取消</el-button>
            </div>
            <el-button v-if="!isShowInputSpecValue" class="add_spec_value_box" type="primary" size="small" @click="handToAddSpecValue(item)">添加规格值</el-button>
          </div>

        </div>
      </el-row>
    </div>
    <!-- sku表格区 -->
    <el-table
      v-if="goodsSkuList.length > 0"
      ref="goodsSkuTaqble"
      :data="goodsSkuList"
      style="width:auto;max-width:60%;margin-top:1rem;margin-bottom:2rem;"
      max-height="500"
      border
      stripe
      highlight-current-row
      empty-text
      fit
    >
      <el-table-column
        v-for="(item,index) in tableColumArray"
        :key="index"
        fixed
        :prop="`spec_value_${index}_object.spec_value`"
        :label="item.spec_name"
        width="150"
        align="center"
      />
      <!--  <template slot-scope="scope">
          <div>{{ scope.row.spec_value_0_object.spec_value }}</div>

        </template>
      </el-table-column> -->

      <el-table-column
        prop="sale_price"
        label="售价"
        width="150"
        align="center"
      >
        <template slot-scope="scope">
          <el-input v-model="scope.row.sale_price" />
        </template>
      </el-table-column>
      <el-table-column
        prop="market_price"
        label="市场价"
        width="150"
        align="center"
      >
        <template slot-scope="scope">
          <el-input v-model="scope.row.market_price" />
        </template>
      </el-table-column>
      <el-table-column
        prop="cost_price"
        label="成本价"
        width="150"
        align="center"
      >
        <template slot-scope="scope">
          <el-input v-model="scope.row.cost_price" />
        </template>
      </el-table-column>
      <el-table-column
        prop="coin"
        label="系统币"
        width="150"
        align="center"
      >
        <template slot-scope="scope">
          <el-input v-model="scope.row.coin" />
        </template>
      </el-table-column>
      <el-table-column
        prop="deduct_coin"
        label="抵扣系统币"
        width="150"
        align="center"
      >
        <template slot-scope="scope">
          <el-input v-model="scope.row.deduct_coin" />
        </template>
      </el-table-column>
      <el-table-column
        prop="share_benefit_type"
        label="佣金扣除类型"
        width="150"
        align="center"
      >
        <template slot-scope="scope">
          <el-select v-model="scope.row.share_benefit_type" placeholder="请选择">
            <el-option label="按固定金额" :value="10" />
            <el-option label="按照售价比例" :value="20" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        v-if="goods.share_benefit_type === 10"
        prop="share_benefit_money"
        label="佣金扣除金额"
        width="220"
        align="center"
      >
        <template slot-scope="scope">
          <div style="display:flex;flex-direction:row">
            <el-input v-model="scope.row.share_benefit_money" />
            <el-tag type="info" style="margin-left:1rem;">单位:元</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        v-if="goods.share_benefit_type === 20"
        prop="share_benefit_rate"
        label="佣金扣除比例"
        width="180"
        align="center"
      >
        <template slot-scope="scope">
          <div style="display:flex;flex-direction:row">
            <el-input v-model="scope.row.share_benefit_rate" />
            <el-tag type="info" style="margin-left:1rem;">%</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="store_number"
        label="库存"
        width="150"
        align="center"
      >
        <template slot-scope="scope">
          <el-row>
            <el-input v-model="scope.row.store_number" />
          </el-row>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        prop="store_warning_number"
        label="预警库存"
        width="150"
        align="center"
      >
        <template slot-scope="scope">
          <el-row>
            <el-input v-model="scope.row.store_warning_number" />
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- sku表格区结束 -->
    <div v-if="goodsSkuList.length > 0 ">
      <el-row v-for="(item,index) in goodsSkuList" :key="index">
        <UploadPicture :limit-number="3" :picture-id.sync="item.sku_picture_id_array" show-content="上传sku图片" :upload-data="{id:0, use_type:20, file_type: '', save_path: 'picture'}" />
      </el-row>
    </div>

  </div>
</template>
<script>
import { getAllGoodsClassBindSpecName, defaultGoodsSpecName, findGoodsSpecName, addCustomGoosSpecName, defaultGoodsSpecValue, findGoodsSpecValue, addGoodsSpecValue } from '@/api/youhu-shop/V1/goods/goodsSpec'

import UploadPicture from '@/pages/component/laravel-fast-api/v1/upload/uploadPicture'

export default
{
  // 组件名称
  name: 'GoodsSpec',
  // 组件
  components:
    {
      UploadPicture
    },
  props:
    {
      // 产品分类id
      goodsClassId: {
        type: Number,
        default: null
      },
      // 产品对象
      goods: {
        type: Object,
        default: function()
        {
          return {}
        }
      },
      // 系统规格名列表
      systemSpecNameArray: {
        type: Array,
        default: function()
        {
          return []
        }
      },
      // 自定义规格名列表
      customSpecNameArray: {
        type: Array,
        default: function()
        {
          return []
        }
      },
      // 商品sku列表
      goodsSkuArray: {
        type: Array,
        default: function()
        {
          return []
        }
      }
    },
  // 数据
  data()
  {
    return {
      // 系统规格名列表
      systemSpecNameList: [],
      // 自定义规格名列表
      customSpecNameList: [],
      // 单个输入的规格名
      singleInputSpecName: null,
      // 建议输入规格名选项
      suggestSpecNameList: [],
      // 规格名定时器
      specNameTimeout: null,
      // 选中的单个规格名
      selectSingleSpecName: null,

      // 控制显示的规格名id
      showGoodsSpecNameId: null,
      // 控制填写规格名值是否显示
      isShowInputSpecValue: false,

      // 单个填写的规格值
      singleInputSpecValue: null,
      // 建议输入规格值选项
      suggestSpecValueList: [],
      // 规格值定时器
      specValueTimeout: null,
      // 选中的单个规格值
      selectSingleSpecValue: null,

      // 产品的sku数组
      goodsSkuList: [],
      // 表格的列名数组
      tableColumArray: []

    }
  },
  // 计算属性
  computed:
    {

    },
  // 监听
  watch:
  {
    // 系统规格名
    systemSpecNameList: {
      handler(value)
      {
        // console.log(value)
        if (value.length > 0)
        {
          this.$emit('update:systemSpecNameArray', value)
        }
      },
      immediate: true,
      deep: true
    },
    // 自定义规格名
    customSpecNameList: {
      handler(value)
      {
        // console.log(value)
        if (value.length > 0)
        {
          this.$emit('update:customSpecNameArray', value)
        }
      },
      immediate: true,
      deep: true
    },
    // 产品是sku数组
    goodsSkuList: {
      handler(value)
      {
        if (value.length > 0)
        {
          // console.log(value)
          this.$emit('update:goodsSkuArray', value)
        }
      },
      immediate: true,
      deep: true
    }

  },
  // 实例创建之前
  beforeCreate()
  {
  },
  // 创建
  created()
  {
  },
  // 挂载之前
  beforeMount()
  {
  },
  // 挂载 --常用
  mounted()
  {
    // console.log(this.goodsClassId)

    if (this.goodsClassId)
    {
      this.getAllGoodsClassBindSpecName(this.goodsClassId)
      this.defaultGoodsSpecName()
    }
  },
  // 更新之前
  beforeUpdate()
  {
  },
  // 跟新后
  updated()
  {
  },
  // 销毁之前
  beforeDestroy()
  {
  },
  // 销毁后
  destroyed()
  {
  },
  // 方法
  methods:
  {
    // 获取产品绑定的规格名
    async getAllGoodsClassBindSpecName(goods_class_id)
    {
      const param = { goods_class_id: goods_class_id }
      let systemSpecNameList = []
      systemSpecNameList = await getAllGoodsClassBindSpecName(param).then(res =>
      {
        return res.data
      })

      // console.log(systemSpecNameList)
      this.systemSpecNameList = systemSpecNameList
    },
    async defaultGoodsSpecName()
    {
      // const param = { limit: 10 }
      const param = { limit: 10 }
      // console.log(param)
      this.suggestSpecNameList = await defaultGoodsSpecName(param).then(res =>
      {
        // console.log(res)
        return res.data
      })
    },
    // 远程查询规格名
    async querySearchAsyncSpecName(queryString, cb)
    {
      this.selectSingleSpecName = null

      this.suggestSpecNameList = await findGoodsSpecName({ find: queryString, spec_type: null }).then(res =>
      {
        return res.data
      })
      const suggestSpecNameList = this.suggestSpecNameList

      const results = queryString ? suggestSpecNameList.filter(this.createSingleInputSpecNameFilter(queryString)) : suggestSpecNameList

      clearTimeout(this.specNametimeout)
      this.specNametimeout = setTimeout(() =>
      {
        cb(results)
      }, 3000 * Math.random())
    },
    // 过滤规格名
    createSingleInputSpecNameFilter(queryString)
    {
      // console.log(queryString)

      return (singleInputSpecName) =>
      {
        return (singleInputSpecName.spec_name.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    // 选择已有的规格名
    handleSelectSpecName(item)
    {
      // console.log(item)
      this.selectSingleSpecName = item
    },
    // 添加自定义规格名
    handleAddCustomSpecName()
    {
      // c onsole.log(this.singleInputSpecName)
      // console.log(this.selectSingleSpecName)

      if (this.singleInputSpecName && !this.selectSingleSpecName)
      {
        addCustomGoosSpecName({ spec_name: this.singleInputSpecName }).then(res =>
        {
          if (res && res.code === 0)
          {
            // console.log(res.data)
            this.customSpecNameList.push(res.data)
          }
        })
      }

      if (this.singleInputSpecName && this.selectSingleSpecName)
      {
        this.customSpecNameList.push(this.selectSingleSpecName)
      }

      this.singleInputSpecName = null
      this.selectSingleSpecName = null
    },
    // 移除已有的规格名
    handleToRemoveCoustomSpecName(item, index)
    {
      // console.log(item)

      if (Object.hasOwn(item, 'selectSpecValueArray') && item.selectSpecValueArray.length > 0)
      {
        this.$message.error('请先清除选中的规格值!')
      }
      else
      {
        const customSpecNameList = this.customSpecNameList
        customSpecNameList.splice(index, 1)
        this.customSpecNameList = customSpecNameList
        this.tableColumArray = []
        this.goodsSkuArray = []
      }
    },
    // 切换为添加规格值
    async handToAddSpecValue(item)
    {
      // console.log('添加规格值')
      // console.log(item)

      // 系统的是 goods_spec_name_id
      if (Object.hasOwn(item, 'goods_spec_name_id'))
      {
        this.showGoodsSpecNameId = item.goods_spec_name_id
      }
      else
      {
        // 自定义的是id
        if (Object.hasOwn(item, 'id'))
        {
          this.showGoodsSpecNameId = item.id
        }
      }

      this.isShowInputSpecValue = true

      this.suggestSpecValueList = await defaultGoodsSpecValue({ goods_spec_name_id: this.showGoodsSpecNameId, limit: 10 }).then(res =>
      {
        return res.data
      })
    },
    // 远程查询规格值
    async querySearchAsyncSpecValue(queryString, cb)
    {
      this.selectSingleSpecValue = null

      this.suggestSpecValueList = await findGoodsSpecValue({ find: queryString, goods_spec_name_id: this.showGoodsSpecNameId }).then(res =>
      {
        return res.data
      })
      const suggestSpecValueList = this.suggestSpecValueList

      const results = queryString ? suggestSpecValueList.filter(this.createSingleInputSpecValueFilter(queryString)) : suggestSpecValueList

      clearTimeout(this.specValuetimeout)
      this.specValuetimeout = setTimeout(() =>
      {
        cb(results)
      }, 3000 * Math.random())
    },
    // 过滤规格名
    createSingleInputSpecValueFilter(queryString)
    {
      // console.log(queryString)

      return (singleInputSpecValue) =>
      {
        return (singleInputSpecValue.spec_value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    // 选择已有的规格值
    handleSelectSpecValue(specValueItem)
    {
      // console.log(item)
      this.selectSingleSpecValue = specValueItem
    },
    // 确认添加规格值
    async handToConfirmSpecValue(item)
    {
      // 检测该对象是否有规格值数组
      if (this.singleInputSpecValue && !this.selectSingleSpecValue)
      {
        let singleSpecValue = null
        singleSpecValue = await addGoodsSpecValue({ spec_value: this.singleInputSpecValue, goods_spec_name_id: this.showGoodsSpecNameId }).then(res =>
        {
          if (res && res.code === 0)
          {
            return res.data
          }
        })

        if (singleSpecValue)
        {
          if (Object.hasOwn(item, 'specValueArray'))
          {
            item.specValueArray.push(singleSpecValue)
          }
          else
          {
            item['specValueArray'] = []
            item.specValueArray.push(singleSpecValue)
          }
        }
      }

      if (this.singleInputSpecValue && this.selectSingleSpecValue)
      {
        if (Object.hasOwn(item, 'specValueArray'))
        {
          item.specValueArray.push(this.selectSingleSpecValue)
        }
        else
        {
          item['specValueArray'] = []
          item.specValueArray.push(this.selectSingleSpecValue)
        }
      }

      this.singleInputSpecValue = null
      this.selectSingleSpecValue = null
      this.showGoodsSpecNameId = null
      this.isShowInputSpecValue = false
      // console.log(this.systemSpecNameList)
    },
    // 取消选择规格值
    handToCancelSpecValue(item)
    {
      this.singleInputSpecValue = null
      this.selectSingleSpecValue = null
      this.showGoodsSpecNameId = null
      this.isShowInputSpecValue = false
    },
    // 选择变化
    handleChangeCheckBox(item, specValueItem)
    {
      // console.log(item)
      // console.log(specValueItem)
      this.processSkuTabelData()
    },
    // 计算处理goodsSkuArray
    processSkuTabelData()
    {
      const totalSpecNameList = [...this.systemSpecNameList, ...this.customSpecNameList]

      // console.log(totalSpecNameList)

      this.tableColumArray = []
      this.goodsSkuList = []

      // 定义是否处理sku数据
      let isProcessGoodsSkuArray = true

      // 第一步,首先处理列名
      totalSpecNameList.forEach((item, key) =>
      {
        // console.log(item)
        let columnObject = {}

        if (Object.hasOwn(item, 'goods_spec_name_id'))
        {
          columnObject = { goods_spec_name_id: item.goods_spec_name_id, spec_name: item.spec_name, spec_code: item.spec_code }
        }
        else
        {
          if (Object.hasOwn(item, 'id'))
          {
            columnObject = { goods_spec_name_id: item.id, spec_name: item.spec_name, spec_code: item.spec_code }
          }
        }

        this.tableColumArray.push(columnObject)

        item['selectSpecValueArray'] = []

        if (Object.hasOwn(item, 'specValueArray') && item.specValueArray.length > 0)
        {
          item.specValueArray.forEach((specValueItem, specValueIndex) =>
          {
            if (Object.hasOwn(specValueItem, 'isSelect') && specValueItem.isSelect)
            {
              item.selectSpecValueArray.push(specValueItem)
            }
          })
        }

        if (item.selectSpecValueArray.length === 0)
        {
          isProcessGoodsSkuArray = false
        }
      })

      if (isProcessGoodsSkuArray)
      {
        const cartesian = (arr) =>
        {
          if (arr.length < 2) return arr[0] || []
          return [].reduce.call(arr, function(col, set)
          {
            const res = []

            if (Array.isArray(col))
            {
              col.forEach(c =>
              {
                if (Array.isArray(set))
                {
                  set.forEach(s =>
                  {
                    const t = [].concat(Array.isArray(c) ? c : [c])
                    t.push(s)
                    res.push(t)
                  })
                }
                else
                {
                  set.selectSpecValueArray.forEach(s =>
                  {
                    const t = [].concat(Array.isArray(c) ? c : [c])
                    t.push(s)
                    res.push(t)
                  })
                }
              })
            }
            else
            {
              col.selectSpecValueArray.forEach(c =>
              {
                if (Array.isArray(set))
                {
                  set.forEach(s =>
                  {
                    const t = [].concat(Array.isArray(c) ? c : [c])
                    t.push(s)
                    res.push(t)
                  })
                }
                else
                {
                  set.selectSpecValueArray.forEach(s =>
                  {
                    const t = [].concat(Array.isArray(c) ? c : [c])
                    t.push(s)
                    res.push(t)
                  })
                }
              })
            }

            return res
          })
        }

        const convertSkuList = cartesian(totalSpecNameList)

        // console.log(convertSkuList)

        const market_price = this.goods.market_price
        const sale_price = this.goods.sale_price
        const cost_price = this.goods.cost_price
        const coin = this.goods.coin
        const deduct_coin = this.goods.deduct_coin
        const share_benefit_type = this.goods.share_benefit_type
        const share_benefit_money = this.goods.share_benefit_money
        const share_benefit_rate = this.goods.share_benefit_rate
        const store_number = this.goods.store_number
        const store_warning_number = this.goods.store_warning_number
        const sku_picture_id_array = []
        // spec_array 原始的规格数组给后端处理

        convertSkuList.forEach((item, key) =>
        {
          const singleSkuData = { 'market_price': market_price, 'sale_price': sale_price, 'cost_price': cost_price, 'coin': coin, 'deduct_coin': deduct_coin, 'share_benefit_type': share_benefit_type, 'share_benefit_money': share_benefit_money, 'share_benefit_rate': share_benefit_rate, 'store_number': store_number, 'store_warning_number': store_warning_number, 'sku_picture_id_array': sku_picture_id_array, 'spec_array': item }

          for (let index = 0; index < this.tableColumArray.length; index++)
          {
            singleSkuData[`spec_value_${index}_object`] = item[index]
          }

          this.goodsSkuList.push(singleSkuData)
        })
      }

      // console.log(this.tableColumArray)
      // console.log(this.goodsSkuList)
    }
  }
}
</script>
<style lang='scss' scoped>
.container_box{
  width: auto;
  max-width: 80wh;
  overflow-x: scroll;
}
.spec_value_array_box{
  display: flex;
  flex-direction: row;
  margin-left: 4rem;
}
.action_box
{
  display: flex;
  flex-direction: row;
  margin-left: 2rem;
  .add_spec_value_box{
    display: flex;
    flex-direction: row;
  }
}
</style>
